<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<style>
    :root {
        --primary-color: #3498db;
        --secondary-color: #2ecc71;
        --dark-color: #34495e;
        --light-color: #ecf0f1;
        --danger-color: #e74c3c;
        --success-color: #2ecc71;
    }

    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background-color: #f8f9fa;
        color: #333;
    }

    .card {
        border-radius: 10px;
        border: none;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    }

    .card-header {
        border-radius: 10px 10px 0 0 !important;
        background-color: var(--primary-color);
    }

    .form-control {
        border-radius: 5px;
        padding: 10px 15px;
        border: 1px solid #ddd;
        text-align: left;
        box-sizing: border-box;
}


    .form-control:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 0.25rem rgba(52, 152, 219, 0.25);
    }

    .btn {
        border-radius: 5px;
        padding: 10px 20px;
        font-weight: 600;
    }

    .btn-info {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
    }

    .btn-success {
        background-color: var(--success-color);
        border-color: var(--success-color);
    }

    .alert {
        border-radius: 5px;
    }

    .db-config-section {
        background-color: #fff;
        padding: 20px;
        border-radius: 5px;
        margin-bottom: 20px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    }

    .form-label {
        font-weight: 600;
        color: var(--dark-color);
        display: flex;
        align-items: center;
        height: 40px;
        margin-bottom: 0;
    }
</style>


{% block content %}
<div class="container d-flex justify-content-center align-items-center" style="min-height: 100vh; max-width: 800px; margin: 0 auto;">
    <div class="card shadow-sm">
        <div class="card-header bg-primary text-white">
            <h4 class="mb-0"> 数据库配置</h4>
        </div>
        <div class="card-body">
            {% if success %}
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                配置保存成功！
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            {% endif %}

            {% if error %}
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                {% if error == 'connection' %}
                连接失败: {{ message }}
                {% elif error == 'save_failed' %}
                保存失败: {{ message }}
                {% else %}
                操作失败: {{ message }}
                {% endif %}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            {% endif %}

            <form id="dbConfigForm" method="post" action="/save_db_config">
                <!-- 数据库类型选择 -->
                <div class="mb-4">
                    <label class="form-label fw-bold mb-2">数据库选用</label>
                    <div class="d-flex gap-4">
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="db_type" id="mysqlRadio" value="mysql" {% if config.type == 'mysql' %}checked{% endif %}>
                            <label class="form-check-label" for="mysqlRadio">MySQL</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="db_type" id="sqliteRadio" value="sqlite" {% if config.type == 'sqlite' %}checked{% endif %}>
                            <label class="form-check-label" for="sqliteRadio">SQLite</label>
                        </div>
                    </div>
                </div>

              <!-- MySQL配置区域 -->
                <div id="mysqlConfig" class="db-config-section {% if config.type != 'mysql' %}d-none{% endif %}">
                    <div class="row g-4 mb-4 align-items-center">
                        <div class="col-md-6 d-flex align-items-center gap-4">
                            <label for="mysqlHost" class="form-label" style="min-width: 80px;">主机地址</label>
                            <input type="text" class="form-control" id="dbHost" name="db_host" value="{{ config.mysql.host }}" required style="height: 40px;">
                        </div>
                        <div class="col-md-6 d-flex align-items-center gap-3">
                            <label for="mysqlPort" class="form-label" style="min-width: 80px;">端口</label>
                            <input type="number" class="form-control" id="dbPort" name="db_port" value="{{ config.mysql.port }}" required style="height: 40px;">
                        </div>
                        <div class="col-md-6 d-flex align-items-center gap-3">
                            <label for="mysqlUser" class="form-label" style="min-width: 80px;">用户名</label>
                            <input type="text" class="form-control" id="dbUser" name="db_user" value="{{ config.mysql.user }}" required style="height: 40px;">
                        </div>
                        <div class="col-md-6 d-flex align-items-center gap-3">
                            <label for="mysqlPassword" class="form-label" style="min-width: 80px;">密码</label>
                            <div class="input-group">
                                
                                    <input type="password" class="form-control" id="dbPassword" name="db_password" value="{{ config.mysql.password }}" style="height: 40px;" maxlength="128">
                                    <button class="btn btn-outline-secondary toggle-password" type="button" data-target="mysqlPassword">
                                        <i class="fas fa-eye"></i>
                                    </button>                               
                          </div>
                        </div>
                        <div class="col-12 d-flex align-items-center gap-4">
                            <label for="mysqlDatabase" class="form-label" style="min-width: 80px;">数据库名</label>
                            <input type="text" class="form-control" id="dbDatabase" name="db_database" value="{{ config.mysql.database }}" required style="height: 40px;">
                        </div>
                    </div>
                </div>


                <!-- SQLite配置区域 -->
                <div id="sqliteConfig" class="db-config-section {% if config.type != 'sqlite' %}d-none{% endif %}">
                    <div class="mb-4">
                        <label for="sqlitePath" class="form-label"> Sqlite 数据库文件路径</label>
                        <div class="input-group">
                            <input type="text" style="width: 600px;" class="form-control" id="sqlitePath" name="db_path" value="{{ config.sqlite.path }}" required>                           
                        </div>
                        <div class="form-text">建议使用绝对路径，如: C:\trade_monitor.db</div>
                    </div>
                </div>

                <div class="d-flex gap-3">
                    <button type="submit" class="btn btn-success ms-auto">保存配置</button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM fully loaded');
        // 密码框眼睛图标切换功能
        const toggleButtons = document.querySelectorAll('.toggle-password');
        toggleButtons.forEach(button => {
            button.addEventListener('click', function() {
                const targetId = this.getAttribute('data-target').replace('mysql', 'db');
                const passwordInput = document.getElementById(targetId);
                if (!passwordInput) return;
                const icon = this.querySelector('i');
                if (passwordInput.type === 'password') {
                    passwordInput.type = 'text';
                    icon.classList.replace('fa-eye', 'fa-eye-slash');
                } else {
                    passwordInput.type = 'password';
                    icon.classList.replace('fa-eye-slash', 'fa-eye');
                }
            });
        });
        // Removed redundant check


        // 数据库类型切换
        const mysqlRadio = document.getElementById('mysqlRadio');
        const sqliteRadio = document.getElementById('sqliteRadio');
        const mysqlConfig = document.getElementById('mysqlConfig');
        const sqliteConfig = document.getElementById('sqliteConfig');

        function toggleConfigSections() {
            if (mysqlRadio.checked) {
                mysqlConfig.classList.remove('d-none');
                sqliteConfig.classList.add('d-none');
            } else {
                mysqlConfig.classList.add('d-none');
                sqliteConfig.classList.remove('d-none');
            }
        }

        mysqlRadio.addEventListener('change', toggleConfigSections);
        sqliteRadio.addEventListener('change', toggleConfigSections);



        // 表单提交前的处理
        const form = document.getElementById('dbConfigForm');
        form.addEventListener('submit', function(event) {
            console.log('表单提交中...');
            // 确保已选择数据库类型
            const dbTypeInputs = form.querySelectorAll('input[name="db_type"]');
            let hasChecked = false;
            dbTypeInputs.forEach(input => {
                if (input.checked) {
                    hasChecked = true;
                    console.log(`选择的数据库类型: ${input.value}`);
                }
            });
            
            if (!hasChecked) {
                event.preventDefault();
                alert('请选择数据库类型（MySQL 或 SQLite）');
                return;
            }
            
            // 显示加载状态
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...';
            
            // 清除旧提示
            const oldAlerts = document.querySelectorAll('.alert-message');
            oldAlerts.forEach(alert => alert.remove());
            
            // 清理Cookie的函数
            function clearCookie(name) {
                document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
            }
            
            // 提交表单
            fetch(form.action, {
                method: 'POST',
                body: new FormData(form)
            })
            .then(response => response.json())
            .then(data => {
                // 无论成功还是失败，都清理所有可能的数据库配置Cookie
                if (data.clear_cookies && Array.isArray(data.clear_cookies)) {
                    data.clear_cookies.forEach(cookieName => {
                        clearCookie(cookieName);
                    });
                }
                
                // 额外清理所有与数据库相关的Cookie
                clearCookie('db_path');
                clearCookie('db_name');
                clearCookie('db_password');
                clearCookie('db_config_leak');
                clearCookie('db_type');
                clearCookie('db_host');
                clearCookie('db_port');
                clearCookie('db_user');
                
                if (data.status === 'success') {
                    // 显示蓝色成功提示
                    const alertDiv = document.createElement('div');
                    alertDiv.className = 'alert alert-primary alert-message alert-dismissible fade show mt-3';
                    alertDiv.style.borderLeft = '4px solid #0d6efd';
                    alertDiv.style.boxShadow = '0 2px 8px rgba(13, 110, 253, 0.2)';
                    alertDiv.innerHTML = `
                        <div class="d-flex align-items-center">
                            <i class="fas fa-check-circle me-2" style="font-size: 1.2rem; color: #0d6efd"></i>
                            <div>
                                <strong>配置文件已更新</strong>
                                <div class="small text-muted">${new Date().toLocaleString()}</div>
                            </div>
                            <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    `;
                    form.parentNode.insertBefore(alertDiv, form.nextSibling);
                } else {
                    // 显示红色失败提示
                    const alertDiv = document.createElement('div');
                    alertDiv.className = 'alert alert-danger alert-message alert-dismissible fade show mt-3';
                    alertDiv.style.borderLeft = '4px solid #dc3545';
                    alertDiv.style.boxShadow = '0 2px 8px rgba(220, 53, 69, 0.2)';
                    alertDiv.innerHTML = `
                        <div class="d-flex align-items-center">
                            <i class="fas fa-exclamation-circle me-2" style="font-size: 1.2rem; color: #dc3545"></i>
                            <div>
                                <strong>配置文件更新失败</strong>
                                <div class="small">${data.message || '未知错误'}</div>
                            </div>
                            <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    `;
                    form.parentNode.insertBefore(alertDiv, form.nextSibling);
                }
            })
            .catch(error => {
                // 清理Cookie
                clearCookie('db_path');
                clearCookie('db_name');
                clearCookie('db_password');
                clearCookie('db_config_leak');
                clearCookie('db_type');
                clearCookie('db_host');
                clearCookie('db_port');
                clearCookie('db_user');
                
                // 显示红色网络错误提示
                const alertDiv = document.createElement('div');
                alertDiv.className = 'alert alert-danger alert-message alert-dismissible fade show mt-3';
                alertDiv.style.borderLeft = '4px solid #dc3545';
                alertDiv.style.boxShadow = '0 2px 8px rgba(220, 53, 69, 0.2)';
                alertDiv.innerHTML = `
                    <div class="d-flex align-items-center">
                        <i class="fas fa-exclamation-circle me-2" style="font-size: 1.2rem; color: #dc3545"></i>
                        <div>
                            <strong>配置文件更新失败</strong>
                            <div class="small">${error.message || '网络错误'}</div>
                        </div>
                        <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                `;
                form.parentNode.insertBefore(alertDiv, form.nextSibling);
            })
            .finally(() => {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            });
            
            // 阻止默认表单提交
            event.preventDefault();
        });


    });
  </script>
{% endblock %}